/*给你一个链表的头节点 head 和一个整数 val ，请你删除链表中所有满足 Node.val == val 的节点，
* 并返回 新的头节点 。
*
* 输入：head = [1,2,6,3,4,5,6], val = 6
* 输出：[1,2,3,4,5]
* */

package newcoder.LinkedList_2;

class ListNode{

    int val;
    ListNode next;
    ListNode(int x){
        val = x;
    }

    public void add(int x){

        ListNode newnode = new ListNode(x);
        if (this.next == null){
            this.next = newnode;
        }else {
            this.next.add(x);
        }
    }

    public void print(){
        System.out.print(this.val);
        if (this.next != null){
            System.out.print("-->");
            this.next.print();
        }
    }

    public ListNode removeElements(ListNode head, int val) {

        ListNode prev = new ListNode(0);
        prev.next = head;
        ListNode p = prev;
        ListNode curr = head;

        while (p.next != null) {

            if (curr.val == val)  p.next = curr.next;
            else p = curr;curr = curr.next;
        }
        return prev.next;
    }
}

public class Leetcode203 {

    public static void main(String[] args) {

        ListNode list = new ListNode(1);
        list.add(2);
        list.add(6);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.print();
        System.out.println();
        list.removeElements(list, 6);
        list.print();
    }
}


